import axios from "axios";
import { getToken,removeToken } from '@/utils/auth'
import { MessageBox, Message } from "element-ui";
import router from "../router/index";

const requset = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 150000, // 请求超时时间
  headers: {'X-Requested-With': 'XMLHttpRequest'}
});

// request拦截器
requset.interceptors.request.use(
  (config) => {
    let time = new Date();
    // 让每个接口携带认证
    if (getToken()) {
      config.headers.Authorization = getToken();
    }
    config.url += `?${time.getTime()}`;
    return config;
  },
  (error) => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);


// respone拦截器
requset.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      // 处理下载文件
      if (
        response.headers &&
        response.headers["content-type"].indexOf("application/vnd.ms-template") >
          -1
      ) {
        return response;
      } else {
        if (response.data.returnCode == "401") {
          Message.error(response.data.returnMgr);
          removeToken()
          router.push({ name: "login" });
        }else if(response.data.returnCode == "200"){
          return response.data;
        }else{
          Message.error(response.data.returnMgr);
          return Promise.reject(response.data);
        }
      }
    } else {
      Message.error(response.data.returnMgr);
      return Promise.reject(response.data);
    }
  },
  (error) => {
    // console.log("err", error.response); // for debug
      // + error.response.data.status
      // MessageBox.alert("系统异常，请联系管理员", "提示", {
      //   confirmButtonText: "确定",
      //   type: "error",
      // });
    return Promise.reject(error);
  }
);

export default requset;
